package IOBaseTest;

import java.io.*;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Vector;

/**
 * Created by yexuan on 2018/3/17.
 * 讲一个文件拆分为多个文件
 */
public class SplitFileDemo {
    public static void main(String[] args) throws IOException{
//        splitFile();
        merge();
    }

    //将一个文件拆分为多个文件
    public static void splitFile() throws IOException{
        FileInputStream pis = new FileInputStream("test1.jpg");
        FileOutputStream pos = null;
        byte[] bytes = new byte[1024*50];
        int num = 0;
        int count = 0;
        while ((num = pis.read(bytes))!=-1){
            pos = new FileOutputStream("split"+count++);
            pos.write(bytes,0,num);
            pos.close();
        }
        pis.close();
    }

    //再将多个文件合并成一个文件
    public static void merge() throws IOException{
        ArrayList<FileInputStream> arrayList = new ArrayList<FileInputStream>();
        arrayList.add(new FileInputStream("split0"));
        arrayList.add(new FileInputStream("split1"));
        final Iterator<FileInputStream> iterator =arrayList.iterator();
        Enumeration<FileInputStream> en = new Enumeration<FileInputStream>() {
            @Override
            public boolean hasMoreElements() {
                return iterator.hasNext();
            }
            @Override
            public FileInputStream nextElement() {
                return iterator.next();
            }
        };

        SequenceInputStream sis = new SequenceInputStream(en);

        FileOutputStream fos = new FileOutputStream("split_hebin");
        byte[] bytes = new byte[1024];
        int num = 0;
        while ((num = sis.read(bytes))!=-1){
            fos.write(bytes,0,num);
        }
        fos.close();
        sis.close();
    }
}
